package cn.hp.service.impl;
import cn.hp.entity.Role;
import cn.hp.entity.RoleMenu;
import cn.hp.mapper.RoleMapper;
import cn.hp.mapper.RoleMenuMapper;
import cn.hp.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Override
    public List<Role> selectRole(Role role) {
        return roleMapper.selectRoleList(role);
    }
    @Override
    public PageInfo<Role> selectRole(Role role, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<Role> list = roleMapper.selectRoleList(role);
        return new PageInfo<>(list);
    }
    @Override
    @Transactional
    public int insertRole(Role role) {
// 第一步：将角色信息插入到role表中
        int k = roleMapper.insertRole(role);
// 第二步：将角色菜单菜单信息插入到role_menu
        Integer[] menuIds = role.getMenuIds();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getId());
            roleMenu.setMenuId(menuId);
            k += roleMenuMapper.insertRoleMenu(roleMenu);
        }
        return k;
    }

    @Override
    @Transactional
    public int upadteRole(Role role) {
        //第一步 删除RoleMenu中的信息
        roleMenuMapper.deleteRoleMenuByRoleId(role.getId());
//第二步 修改角色信息
        int k = roleMapper.updateRole(role);
//第三步 将角色菜单信息再次插入role_menu
        Integer[] menuIds = role.getMenuIds();
        for (Integer menuId : menuIds) {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getId());
            roleMenu.setMenuId(menuId);
            k += roleMenuMapper.insertRoleMenu(roleMenu);
        }
        return k;
    }


    @Override
    @Transactional
    public int deleteRoleById(Integer id) {
        int k = roleMenuMapper.deleteRoleMenuByRoleId(id);
        return roleMapper.deleteRoleById(id);
    }
}
